<template xmlns="http://www.w3.org/1999/html">
  <el-row :gutter="20">
    <div v-if="isDataLoaded" class="select-container"
         style="margin-left:10px;margin-top: 0;margin-bottom: 10px; display: flex; align-items: center">
      <div class="select-title" style="margin-right: 10px;color: #373a3c;">选择项目:</div>
      <el-select
          v-model="selected"
          filterable
          placeholder="输入搜索或下拉选择"
          style="width: 450px;"
          :clearable="true"
          :popper-append-to-body="false"
          @change="handleSelectionChange"
      >
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>
    <div class="select-container"
         style="margin-left:10px;margin-top: 0;margin-bottom: 10px; display: flex; align-items: flex-end"
    >
      <el-button
          type="primary"
          style="width: 120px;align-items: center"
          :loading="isPreLoading"
          @click="getPreprocess"
      >
        {{ isPreLoading ? '预处理中...' : '预处理' }}
      </el-button>
      <span class="tooltip">生成Token/AST/PDG</span>

      <el-button
          type="success"
          style="width: 120px;align-items: center"
          :loading="isTraining"
          @click="startFileTraining"
      >
        {{ isTraining ? '训练中...' : '训练模型' }}
      </el-button>
      <span class="tooltip">根据选择的项目训练新模型</span>
      <el-button
          type="warning"
          style="width: 120px;align-items: center"
          :loading="isTestLoading"
          @click="getTestResult"
      >
        {{ isPreLoading ? '测试中...' : '测试模型' }}
      </el-button>
      <span class="tooltip">使用已有模型</span>
      <el-button
          type="info"
          style="width: 120px;align-items: center"
          :loading="isEvaluateLoading"
          @click="getEvaluateList"
      >
        {{ isEvaluateLoading ? '获取中...' : '评价指标' }}
      </el-button>
      <span class="tooltip">查看最新评价分数</span>
    </div>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-card shadow="hover" :body-style="{ height: '420px',}">
        <div style="margin: 5px;align-items: center"> 源代码文件</div>
        <file-location/>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card shadow="hover" :body-style="{ height: '420px' }" style="margin-bottom: 10px">
        <div style="margin: 5px;align-items: center"> 缺陷报告</div>
        <report-location/>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-card shadow="hover" :body-style="{ height: '420px' }">
        <div style="margin: 5px;align-items: center"> 可疑语句列表</div>
        <!--        展示可疑语句列表以及分数-->
        <el-table
            :data="RecommendedFileList"
            border
            max-height="350"
            size=small
            class="file-table"
            style="margin-bottom: 10px"
        >
          <!--          展示一栏序号-->
          <el-table-column label="序号" type="index" width="50" style="align-items: center"></el-table-column>
          <el-table-column label="项目名称" prop="project_name"
                           style="width: auto;align-items: center"></el-table-column>
          <el-table-column label="文件位置" prop="file_path" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="语句位置" prop="sentence" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="可疑分数" prop="score" style="width: auto; align-items: center"></el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card shadow="hover" :body-style="{ height: '420px' }">
        <div style="margin: 5px;align-items: center"> 评价指标</div>
        <!--        展示分数-->
        <el-table
            :data="RecommendedScoreList"
            border
            max-height="350"
            size=small
            class="file-table"
            style="margin-bottom: 10px"
        >
          <!-- 展示一栏序号-->
          <el-table-column label="序号" type="index" width="50" style="align-items: center"></el-table-column>
          <el-table-column label="项目" prop="project_name" style="width: auto;align-items: center"></el-table-column>
          <el-table-column label="TOP_1" prop="top1" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="TOP_5" prop="top5" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="TOP_10" prop="top10" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="MRR" prop="mrr_score" style="width: auto; align-items: center"></el-table-column>
          <el-table-column label="MAP" prop="map_score" style="width: auto; align-items: center"></el-table-column>
        </el-table>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts" name="dashboard">
import {registerMap, use} from 'echarts/core';
import {BarChart, LineChart, MapChart, PieChart} from 'echarts/charts';
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  VisualMapComponent,
} from 'echarts/components';
import {CanvasRenderer} from 'echarts/renderers';
import chinaMap from '@/utils/china';
import {ElMessage, ElOption, ElSelect} from 'element-plus'
import axios from "axios";
import {onMounted, ref} from "vue";
import FileLocation from "@/views/system/file-location.vue";
import ReportLocation from "@/views/system/report-location.vue";
import EventBus from "@/utils/eventBus";


const globalApiUrl = import.meta.env.VITE_API_URL

console.log('Global API URL:', globalApiUrl);

const projectsUrl = globalApiUrl + '/projects';

let totalProject = 0
// 下拉选项
let options = []
let isDataLoaded = ref(false); // 用于标记数据是否加载完成
let RecommendedFileList = ref([]); // 推荐列表
let RecommendedScoreList = ref([]); // 推荐列表

const selected = ref(null);  // 用来存储选中的项目值
let srcFileList = ref([]); // 获取当前目录下的源代码文件列表
let reportFileList = ref([]); // 获取当前目录下的缺陷报告文件列表
const isPreLoading = ref(false)
const isTraining = ref(false)
const isTestLoading = ref(false)
const isEvaluateLoading = ref(false)

const getTestResult = () => {
  isTestLoading.value = true
  // 延时3s
  setTimeout(() => {
    isTestLoading.value = false
  }, 3000)
  ElMessage.warning("暂不支持")
}

// 获取项目id
const getData = async () => {
  // 向后端请求获取projects
  await axios.get(projectsUrl, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + localStorage.getItem('access_token')
    },
    params: {
      page: 1,
      size: 1000,
    }
  }).then((response) => {
    // 遍历response.data.data.data，填入options
    totalProject = response.data.data.data.length
    for (let i = 0; i < totalProject; i++) {
      options.push({
        value: response.data.data.data[i].id,
        label: response.data.data.data[i].name,
      })
    }
    // 设置默认值为 options 中的第一个项
    if (options.length > 0 && !selected.value) {
      selected.value = options[0].value;
    }
    isDataLoaded.value = true; // 数据加载完成
  })
};

// 选择值时发起请求或处理逻辑
const handleSelectionChange = () => {
  console.log('选中的项目 ID:', selected.value);
  // 发起新的请求或者跳转路由
  fetchSrcFiles();
  fetchReportFiles();
  getEvaluateList();
  getRecommendedList();
  EventBus.$emit('update-src-data', null);
  EventBus.$emit('update-report-data', null);
};

const filesUrl = globalApiUrl + '/files'; // 后端获取文件夹的 URL
// 获取源代码文件文件列表
const fetchSrcFiles = async () => {
  if (!selected.value) return;
  try {
    const response = await axios.get(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: selected.value.toString() + '/src'} // 传递当前路径
    });
    if (response.data.result) {
      srcFileList.value = response.data.data;
      localStorage.setItem('srcFileList', JSON.stringify(srcFileList.value));
      localStorage.setItem('srcCurrentPath', selected.value.toString() + '/src');
    } else {
      ElMessage.error('获取项目文件列表失败,请联系管理员');
    }
  } catch (error) {
    console.error('Error fetching file list:', error);
    ElMessage.error('获取项目文件列表失败,请稍后重试');
  }
};
// 获取缺陷报告文件文件列表
const fetchReportFiles = async () => {
  if (!selected.value) return;
  try {
    const response = await axios.get(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: selected.value.toString() + '/report'} // 传递当前路径
    });
    if (response.data.result) {
      reportFileList.value = response.data.data;
      localStorage.setItem('reportFileList', JSON.stringify(reportFileList.value));
      localStorage.setItem('reportCurrentPath', selected.value.toString() + '/report');
    } else {
      ElMessage.error('获取项目文件列表失败,请联系管理员');
    }
  } catch (error) {
    console.error('Error fetching file list:', error);
  }
};

// 获取预处理的数据
const getPreprocess = async () => {
  const preprocessUrl = globalApiUrl + '/preprocess';
  isPreLoading.value = true;

  console.log("isDataLoaded->:", isDataLoaded.value)
  try {
    const response = await axios.get(preprocessUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {
        path: selected.value.toString()
      }
    });
    if (response.data.result) {
      ElMessage.success("预处理完成")
    } else {
      ElMessage.error("预处理失败，请联系管理员")
    }
  } catch (error) {
    ElMessage.error("预处理失败，请稍后再试")
  } finally {
    isPreLoading.value = false;
  }
}

// 获取预处理的数据
const startFileTraining = async () => {
  const preprocessUrl = globalApiUrl + '/sen-training';
  isTraining.value = true;

  try {
    const response = await axios.get(preprocessUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {
        path: selected.value.toString()
      }
    });
    if (response.data.result) {
      RecommendedFileList.value = response.data.data
      await getRecommendedList()
      await getEvaluateList()
      ElMessage.success("训练完成")
    } else {
      ElMessage.error("训练失败，请联系管理员")
    }
  } catch (error) {
    ElMessage.error("训练失败，请稍后再试")
  } finally {
    isTraining.value = false;
  }
}

// 获取最新的推荐列表
const getRecommendedList = async () => {
  const preprocessUrl = globalApiUrl + '/sen-recommend';
  try {
    const response = await axios.get(preprocessUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {
        path: selected.value.toString()
      }
    });
    if (response.data.result) {
      RecommendedFileList.value = response.data.data
    } else {
      ElMessage.error("获取推荐列表失败，请联系管理员")
    }
  } catch (error) {
    ElMessage.error("获取推荐列表失败，请稍后再试")
  }
}
//   获取最新的评价分数
const getEvaluateList = async () => {
  isEvaluateLoading.value = true
  const evaluateUrl = globalApiUrl + '/score';
  try {
    const response = await axios.get(evaluateUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {
        path: selected.value.toString(),
        flag: "sen"
      }
    });
    if (response.data.result) {
      RecommendedScoreList.value = response.data.data
    } else {
      ElMessage.error("获取评价分数失败，请联系管理员")
    }
  } catch (error) {
    ElMessage.error("获取评价分数失败，请稍后再试")
  } finally {
    isEvaluateLoading.value = false
  }
}

// 页面加载时调用 getData
onMounted(async () => {
  await getData();
  await fetchSrcFiles();
  await fetchReportFiles();

  await getRecommendedList();
  await getEvaluateList();
});

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  LineChart,
  PieChart,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  VisualMapComponent,
  MapChart,
]);
registerMap('china', chinaMap);
</script>


<style scoped>
.select-container {
  padding: 20px 20px 20px 20px;
  background-color: #fff;
  margin-bottom: 40px;
  border: 1px solid #ddd;
  border-radius: 5px
}

.el-button .custom-loading .circular {
  margin-right: 6px;
  width: 18px;
  height: 18px;
  animation: loading-rotate 2s linear infinite;
}

.tooltip {
  display: flex;
  align-items: center;
  gap: 10px; /* 按钮和文字之间的间距 */
  color: gray; /* 设置文字颜色为灰色 */
  font-size: 10px; /* 文字较小 */
  margin-left: 10px;
  margin-right: 30px;
}

</style>
